package celiasoft.itasalib.query.resultparser;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DomHandler {
	
	@SuppressWarnings("unused")
	private static final String TAG = "itasalib.DomHandler";

	/**
	 * Returns element text value.
	 * 
	 * @param elem
	 *            the element
	 * @return Element value, null otherwise
	 */
	public static String getElementValue(Node elem) {
		Node kid;
		if (elem != null) {
			if (elem.hasChildNodes()) {
				for (kid = elem.getFirstChild(); kid != null; kid = kid
						.getNextSibling()) {
					if (kid.getNodeType() == Node.TEXT_NODE) {
						return kid.getNodeValue();
					}
				}
			}
		}
		return null;
	}

	/**
	 * Returns the value of the searched element.
	 * 
	 * @param e
	 *            the base element
	 * @param str
	 *            the name of the element we are searching for
	 * @return Element value, or null.
	 */
	public static String getValue(org.w3c.dom.Element e, String str) {
		NodeList n = e.getElementsByTagName(str);
		
		if(n == null){
			return null;
		}
		
		return getElementValue(n.item(0));
	}
	
	/**
	 * Returns the value of the searched document.
	 * 
	 * @param doc
	 *            the base document
	 * @param str
	 *            the name of the element we are searching for
	 * @return Element value, or null.
	 */
	public static String getValue(Document doc, String str) {
		NodeList n = doc.getElementsByTagName(str);
		
		if(n == null){
			return null;
		}
		return getElementValue(n.item(0));
	}

}
